package drawingBoard.memento;

import java.util.ArrayList;
import java.util.List;

public class CareTaker {

    private static CareTaker instance;
    //定义一个集合来存储多个备忘录
    private List<Memento> mementoList=new ArrayList<Memento>();  //聚合
    public int index=-1;

    //单例模式（懒汉式，线程安全）
    public static synchronized CareTaker getInstance() {
        if (instance==null) {
            instance=new CareTaker();
        }
        return instance;
    }

    public void add(Memento state){  //添加状态
        index++;
        //mementoList=mementoList.subList(0,index);  //子表不包括index那一项
        mementoList.add(state);
    }

    public Memento get(int index){  //根据index获取状态
        return mementoList.get(index);
    }

    public int size(){  //获取长度
        return mementoList.size();
    }

    public Memento Undo(){  //撤销
        if(index>0){
            if(index==mementoList.size()-1) index--;
            index--;
            return get(index);
        }
        else{
            return get(0);
        }
    }

    public Memento Redo(){  //恢复
        if(index<mementoList.size()){
            if(index==mementoList.size()-2) index++;
            index++;
            if(index>=mementoList.size()) index=mementoList.size()-1;
            return get(index);
        }
        else{
            return get(mementoList.size()-1);
        }
    }
}
